//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_doc_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type DocContentDbItem struct {
	DocId   string `bson:"_id"`
	Content string `bson:"content"`
}

type _DocContentDao struct {
	mc *mongo.Collection
}

func newDocContentDao(db *mongo.Database) (*_DocContentDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_DOC + "doc_content")
	return &_DocContentDao{mc: mc}, nil
}

func (db *_DocContentDao) Insert(ctx context.Context, dbItem *DocContentDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_DocContentDao) Update(ctx context.Context, docId, content string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": docId}, bson.M{"$set": bson.M{"content": content}})
	return err
}

func (db *_DocContentDao) Exist(ctx context.Context, docId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": docId})
	return count > 0, err
}

func (db *_DocContentDao) Get(ctx context.Context, docId string) (*DocContentDbItem, error) {
	retItem := &DocContentDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": docId}).Decode(retItem)
	return retItem, err
}

func (db *_DocContentDao) ListById(ctx context.Context, docIdList []string) ([]*DocContentDbItem, error) {
	if len(docIdList) == 0 {
		return []*DocContentDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": docIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*DocContentDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_DocContentDao) Remove(ctx context.Context, docId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": docId})
	return err
}
